package cyberdict.scr;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TableRow.LayoutParams;



public class CyberDict extends Activity {
    /** Called when the activity is first created. */
	final String masterPath= "/sdcard/CyberDict/data";
	int selectedIndex;
	DictEngine mDE;
    @Override
    
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final AutoCompleteTextView word_enter = (AutoCompleteTextView) findViewById(R.id.word_enter);
        final WebView word_view = (WebView) findViewById(R.id.word_view);
        //--------------Button DICT-------------------//
        final ImageButton dict_manager= (ImageButton) findViewById(R.id.button_Dict);
        dict_manager.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				manageDictionary();
				mDE= new DictEngine(masterPath, dflist.items.get(selectedIndex).fileName);
			}
		});
        
        //------------------------------------------------//
        final ImageButton about= (ImageButton) findViewById(R.id.buttonAbout);
        about.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				word_view.loadDataWithBaseURL (null, "</br><p align=center><font size=6 color=blue><b>CyberDict – v1.0</b></font></br><font size=5 >Tatung Vo</font></br><font size=4 >TH. Tin K30</font></br><font size=4 >&#272;H. Quy Nh&#417;n</font></br><font size=4 >Email: <a href=\"mailto:tatungvo@gmail.com\">tatungvo@gmail.com</a></font></br>© 2010</p>", "text/html","UTF-8","about:blank");
			}
		});
        word_view.setWebViewClient(new WebViewClient() 
        {
        	       	
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView word_view, String url)
        	{
        		try
        		{
            		String arrUrlPart[] = url.split("://");
            		
            		
            		curDB= mDE.getCursorWordList(arrUrlPart[1].toString());
            		
                    if (curDB.getCount()>0)
                    {
                    	curDB.moveToFirst();
                    	//word_view.setText(curDB.getString(curDB.getColumnIndex("content")));
                    	word_enter.setText(arrUrlPart[1].toString());
                    	word_view.loadDataWithBaseURL (null, curDB.getString(curDB.getColumnIndex("content")), "text/html","UTF-8","about:blank");
                    	//word_view.setText("co ton tai");
                    }
        		}
        		catch (Exception ex)
        		{
        			ex.printStackTrace();
        		}
        		return true;
        	}
        });
        
        //final TwoLineListItem list_Dict= (TwoLineListItem) findViewById(R.id.TwoLineListItem01);
        
        dflist= new DictFileList(masterPath, "");
        //int itemIndexDict=0;
        mDE= new DictEngine(masterPath, dflist.items.get(selectedIndex).fileName);
        mAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);
        word_enter.setAdapter(mAdapter);
        
        word_enter.setOnKeyListener(new OnKeyListener() {            
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
            	if (!mAdapter.isEmpty()) mAdapter.clear();
            	if (event.getAction() == KeyEvent.ACTION_DOWN 
                        && keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                    //try{
            		curDB= mDE.getCursorWordList(word_enter.getText().toString());
            		
                    if (curDB.getCount()>0)
                    {
                    	curDB.moveToFirst();
                    	//word_view.setText(curDB.getString(curDB.getColumnIndex("content")));
                    	word_view.loadDataWithBaseURL (null, curDB.getString(curDB.getColumnIndex("content")), "text/html","UTF-8","about:blank");
                    	//word_view.setText("co ton tai");
                    }
                    //}
                    //catch (Exception e){}
                    
                    
                    //word_view.setText(mDE.toString());
                   //if (mDE.setDatabaseFile(masterPath, dflist.items.get(0).fileName)==true)
                    //	word_view.setText("adfsdf");
                    
                    return true;
                    
                }
                else {
                	if (word_enter.getText().length()>=2)// && event.getAction()!=KeyEvent.KEYCODE_DEL)
                	{
                		
                		curDB= mDE.getCursorWordList(word_enter.getText().toString());
                		
                		
                		int i=0;
                		String word;
                		int wordID;
                		int wordColumn=curDB.getColumnIndex("word");
                		int idColumn=curDB.getColumnIndex("id");
                		//word_view.setText(wordColumn+"  "+idColumn);
                		if (!mLSTCurrentWord.isEmpty())
                			mLSTCurrentWord.clear();
                		if (!mLSTCurrentWordId.isEmpty())
                			mLSTCurrentWordId.clear();
                		if (!mAdapter.isEmpty())
                			mAdapter.clear();
                		
                		//try{
                		curDB.moveToFirst();
                		
                		//word_view.setText(Utility.decodeContent(curDB.getString(wordColumn)));
                		
                		do
                		{
                			//if (!curDB.isNull(idColumn) && !curDB.isNull(wordColumn))
                			{
                				word=Utility.decodeContent(curDB.getString(wordColumn));
                				wordID=curDB.getInt(idColumn);
                    			//try{
                    			mLSTCurrentWord.add(i,word);
                    			mLSTCurrentWordId.add(i,new Integer(wordID));
                    			mAdapter.insert(word, i);
                    			word_enter.setAdapter(mAdapter);
                			}
                			i++;
                			
                			//}
                			//catch(Exception e){}
                			
                		}
                		while (curDB.moveToNext() && i<15);
                		//}
                		//catch(Exception e){}
                		
                		mLSTCurrentWord.toArray(arrWord_tmp);
                		//word_enter.showDropDown();
                		
                	}
                	 
                		
                
                	
                	
                	
                	return false;
                }
            	
            	
            }   	
            
            
        });
        
        
        
    }
    private DictFileList dflist;
    private DictFile mDBFile;
    private ArrayList<String> mLSTCurrentWord = new ArrayList<String>();
    private ArrayList<Integer> mLSTCurrentWordId = new ArrayList<Integer>();
    private ArrayAdapter<String> mAdapter;
    final String arrWord_tmp[]= new String [15];Cursor curDB=null;
    static final private int VIEW_RADIO_ID = 400;
    
    
    public void manageDictionary()
	{
		setContentView(R.layout.dbmanager);
		ScrollView ll = (ScrollView) findViewById(R.id.lstDb);
		final RadioGroup rg = new RadioGroup(this);
		rg.setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.FILL_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT));
		rg.setOrientation(RadioGroup.VERTICAL);
		//Log.d(MAIN_TAG, "Size of mDBList = " + mDBList.items.size());
		for (int i=0; i < dflist.items.size(); i++)
		{
            // Create a TextView to house the value of the after-tax income
            RadioButton rb = new RadioButton(this);
            rb.setId(VIEW_RADIO_ID + i);
            rb.setText(dflist.items.get(i).dictName);
            rb.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
            
            rg.addView(rb,i);
            //if (mDBFile != null && mDBFile.fileName.equals(dflist.items.get(i).fileName))
            //{
            //	rg.check(VIEW_RADIO_ID + i);
            //}
            
            //Log.d(MAIN_TAG,mDBList.items.get(i).path + " |  " + mDBList.items.get(i).fileName);
		}
		rg.check(VIEW_RADIO_ID + selectedIndex);
        ll.addView(rg);
        Button btnOk = (Button) findViewById(R.id.btnOk);
        btnOk.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View v)
        	{
        		//setContentView(R.layout.main);
        		selectedIndex = rg.getCheckedRadioButtonId()-VIEW_RADIO_ID;
        		if (selectedIndex < 0)
        		{
        			selectedIndex = 0;
        		}
        		onCreate(new Bundle());
        		
        		//mDBFile.reset();
        		//mDBFile = dflist.items.get(selectedIndex - VIEW_RADIO_ID);
        		//Log.i(MAIN_TAG,"Loaded dictionary " + mDBFile.path + " | " + mDBFile.fileName);
        		
                //setContentView(R.layout.main);
                
        		
        	}
        });
        
	}
}